package com.alquimia.identityaccess.domain.model;

import java.io.Serializable;
import java.util.regex.Pattern;

/**
 * Created by Ivo on 14/07/2014.
 */
public final class UserDescriptor implements Serializable {

    private UserId userId;
    private String username;
    private String emailAddress;

    public UserDescriptor(UserId aUserId, String aUsername, String aEmailAddress) {
        this();

        setUserId(aUserId);
        setUsername(aUsername);
        setEmailAddress(aEmailAddress);
    }

    public static UserDescriptor nullUserDescriptorInstance() {
        return new UserDescriptor();
    }

    @Override
    public boolean equals(Object anObject) {
        boolean equalObjects = false;

        if (anObject != null && this.getClass() == anObject.getClass()) {
            UserDescriptor typedObject = (UserDescriptor) anObject;
            equalObjects =
                    this.emailAddress().equals(typedObject.emailAddress()) &&
                            this.userId().equals(typedObject.userId()) &&
                            this.username().equals(typedObject.username());
        }

        return equalObjects;
    }

    @Override
    public int hashCode() {
        int hashCodeValue =
                +(9429 * 263)
                        + this.emailAddress().hashCode()
                        + this.userId().hashCode()
                        + this.username().hashCode();

        return hashCodeValue;
    }

    @Override
    public String toString() {
        return "DescriptorUsuario [emailAddress=" + emailAddress
                + ", userId=" + userId + ", firstName=" + username + "]";
    }

    protected UserDescriptor() {
        super();
    }

    public UserId userId() {
        return userId;
    }

    private void setUserId(final UserId aUserId) {

        if (aUserId == null)
            throw new NullPointerException("Usuario id no debe ser nulo.");

        userId = aUserId;
    }

    public String username() {
        return username;
    }

    private void setUsername(final String aUsername) {

        if (aUsername.isEmpty())
            throw new IllegalArgumentException("El firstName de user es requerido.");

        username = aUsername;
    }

    public boolean isNullDescriptor() {
        return this.emailAddress() == null || this.userId() == null || this.username() == null;
    }

    public String emailAddress() {
        return emailAddress;
    }

    private void setEmailAddress(final String aEmailAddress) {

        if (aEmailAddress.isEmpty())
            throw new IllegalArgumentException("El emailAddress es requerido.");

        if (!Pattern.matches("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", aEmailAddress))
            throw new IllegalArgumentException("El emailAddress debe tener un formato válido.");

        emailAddress = aEmailAddress;
    }
}
